package com.employ.admin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.employ.admin.common.Result;
import com.employ.admin.entity.User;
import com.employ.admin.mapper.UserMapper;
import com.employ.admin.service.UserService;
import com.employ.admin.utils.Base64;
import com.employ.admin.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Resource
    UserMapper userMapper;


    @PutMapping
    public Result<?> update(@RequestBody User user) {

        userMapper.updateById(user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {

        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.error("500", "用户名或密码不能为空");

        }

        Base64 b6 = new Base64();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", user.getUsername());
        map.put("password", b6.getBase64(user.getPassword()));
        String token = JwtUtils.createToken(map);
        System.out.println(token);

        int result = JwtUtils.verifyToken(token);
        if (result == 0) {
            System.out.println("验证token:成功");
        } else {
            System.out.println("验证token:失败");

        }

        User us = userMapper.findUserByName(user.getUsername());
        us.setToken(token);

        Map<String, Object> hashmap = JwtUtils.parseToken(token);
        System.out.println(hashmap);

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));//.eq(User::getPassword, user.getPassword())).eq(User::getPassword, user.getPassword()))
        if (res == null) {
            return Result.error("-1", "用户名或密码错误");
        }
        res.setToken(token);
        return Result.success(res);
    }

}
